import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:5000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 自动添加token
api.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    const token = authStore.token
    
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理token过期
api.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    const originalRequest = error.config
    
    // 如果是401错误且不是刷新token请求，且不是登录请求
    if (error.response?.status === 401 && 
        !originalRequest._retry && 
        !originalRequest.url?.includes('/refresh') &&
        !originalRequest.url?.includes('/login')) {
      
      originalRequest._retry = true
      
      try {
        const authStore = useAuthStore()
        const refreshToken = authStore.refreshToken
        
        if (!refreshToken) {
          throw new Error('没有刷新令牌')
        }
        
        // 刷新token
        const refreshResponse = await axios.post('http://localhost:5000/api/user/refresh', {
          refresh_token: refreshToken
        })
        
        if (refreshResponse.data.code === 200) {
          const { access_token, refresh_token, user_info } = refreshResponse.data.data
          
          // 更新store中的token
          authStore.token = access_token
          authStore.refreshToken = refresh_token
          authStore.user = user_info
          
          // 更新localStorage
          localStorage.setItem('access_token', access_token)
          localStorage.setItem('refresh_token', refresh_token)
          localStorage.setItem('user_info', JSON.stringify(user_info))
          
          // 重新发送原请求
          originalRequest.headers.Authorization = `Bearer ${access_token}`
          return api(originalRequest)
        } else {
          throw new Error(refreshResponse.data.message || '刷新token失败')
        }
      } catch (refreshError) {
        console.error('刷新token失败:', refreshError)
        
        // 刷新失败，清除认证信息并跳转到登录页
        const authStore = useAuthStore()
        authStore.token = null
        authStore.refreshToken = null
        authStore.user = null
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        localStorage.removeItem('user_info')
        window.location.href = '/login'
      }
    }
    
    // 处理其他错误
    if (error.response?.status >= 500) {
      ElMessage.error('服务器错误，请稍后重试')
    } else if (error.response?.status === 404) {
      ElMessage.error('请求的资源不存在')
    } else if (error.response?.status === 403) {
      ElMessage.error('权限不足')
    }
    
    return Promise.reject(error)
  }
)

export default api